<template>
  <div>
    <el-form ref="queryForm"
      class="query-form"
      :model="queryParams"
      size="small"
      :inline="true">
      <el-form-item label="状态"
        prop="status">
        <el-select v-model="queryParams.status"
          @change="handleQuery">
          <el-option key="all"
            label="全部"
            :value="null"/>
          <el-option
            label="已上架"
            value="published" />
          <el-option
            label="未上架"
            value="stop" />
        </el-select>
      </el-form-item>
      <el-form-item class="big-query" label="关键词"
        prop="keyword">
        <el-input v-model="queryParams.keyword"
          placeholder="输入加购包ID、名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
          @clear="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
          size="small"
          @click="handleQuery">搜索</el-button>
        <el-button size="small"
          @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-button type="primary"
        icon="el-icon-plus"
        style="margin-bottom:10px"
        size="small"
        @click="handleAdd">新增</el-button>
    </div>
    <el-table v-loading="loading"
      @sort-change="onSortChange"
      :data="dataList">
      <el-table-column label="加购包标识ID"
        min-width="120"
        prop="addition_id" />
      <el-table-column label="加购包名称"
        min-width="120"
        prop="name">
      </el-table-column>
      <el-table-column label="计费单位及数量"
        min-width="120"
        prop="icon">
        <template slot-scope="scope">
          {{ getItemsSetting(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="权益权重"
        width="120"
        sortable="custom"
        prop="weight" />
      <el-table-column label="描述"
        min-width="120"
        prop="description">
      </el-table-column>
      <el-table-column label="状态"
        width="100"
        >
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 'published' ? 'success' : 'danger'"
            disable-transitions>{{ scope.row.status === 'published' ? '已上架' : '待上架' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作"
        width="120"
        fixed="right">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="text"
            @click="handleUpdate(scope.row)">修改</el-button>
          <el-button
            size="small"
            type="text"
            @click="handleSale(scope.row)">{{ scope.row.status==='stop'?'上架':'下架' }}</el-button>
          <el-button
            :disabled="scope.row.status === 'published'"
            size="small"
            type="text"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.page_size"
      @pagination="getList" />
    <el-dialog :title="form.id?'编辑':'添加'+'加购包'"
      :visible.sync="open"
      width="650px"
      :close-on-click-modal="false"
      @closed="onDialogClosed">
      <el-form ref="form"
        :model="form"
        :rules="rules"
        label-width="120px">
        <el-form-item label="加购包标识ID" prop="addition_id">
          <el-input v-model.trim="form.addition_id" :disabled="!!form.id" maxlength="32"/>
        </el-form-item>
        <el-form-item label="加购包名称" prop="name">
          <el-input v-model.trim="form.name" maxlength="15"/>
        </el-form-item>
        <el-form-item label="权益包描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入权益包描述"/>
        </el-form-item>
        <el-form-item label="权重" prop="weight">
          <el-input-number v-model="form.weight" :precision="0" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="权益配置" prop="items">
          <el-form-item v-for="(item,index) in form.items" :key="item.key" :prop="'items.' + index" :rules="rules.settings" style="margin-bottom: 22px;">
            <el-select v-model="form.items[index].item_type" style="width: 180px;">
              <el-option v-for="item in chargeUnitList" :value="item.unit_id" :label="item.internal_name" :key="item.unit_id"></el-option>
            </el-select>
            <el-input-number v-model="form.items[index].count" :precision="0" :min="0" controls-position="right" class="ml10"></el-input-number>
            <el-button v-show="form.items.length-1!==index" class="ml10" @click="onDeleteItems(index)">
              <i class="el-icon-minus"></i>
            </el-button>
            <el-button v-show="form.items.length-1===index"
              class="ml10"
              @click="onAddItems()"><i class="el-icon-plus"></i></el-button>
          </el-form-item>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary"
          :loading="saveLoading"
          @click="submitForm('stop')">确 认</el-button>
        <el-button type="primary"
          :loading="saveLoading"
          v-if="!form.id"
          @click="submitForm('published')">新增并上架</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getPackageList, addPackage, updatePackage } from '@/api/addition'
import { getChargeUnit } from '@/api/system'
export default {
  name: 'ChargeFormula',
  data () {
    const validateSettings = (rule, value, callback) => {
      if (!value.item_type) {
        callback(new Error('计费单位不能为空'))
      } else if (!value.count) {
        callback(new Error('请输入数量'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      saveLoading: false,
      chargeUnitList: [],
      queryParams: {
        status: null,
        keyword: '',
        page: 1,
        page_size: 10
      },
      dataList: [],
      total: 0,
      open: false,
      form: {
        id: null,
        name: '',
        addition_id: '',
        description: '',
        weight: 0,
        items: [
          { key: Date.now(), item_type: null, count: undefined }
        ]
      },
      rules: {
        name: [{ required: true, message: '加购包名称不能为空', trigger: 'blur' }],
        fn_num: [{ required: true, message: '不能为空', trigger: 'blur' }],
        items: [
          { required: true, type: 'array', message: '权益不能为空', trigger: 'blur' }
        ],
        settings: [
          { validator: validateSettings, trigger: [] }
        ]
      }
    }
  },
  created () {
    getChargeUnit().then(res => {
      this.chargeUnitList = res.data.list
    })
    this.getList()
  },
  methods: {
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    onSortChange ({ prop, order }) {
      this.queryParams.sort_field = order ? prop : null
      this.queryParams.sort_method = order === 'descending' ? 'desc' : 'asc'
      this.getList()
    },
    handleAdd () {
      this.open = true
    },
    getList () {
      this.loading = true
      getPackageList(this.queryParams).then(res => {
        const data = res.data || {}
        this.dataList = (data.list || []).map(row => {
          row.items = row.items.map(item => {
            const setting = JSON.parse(item.setting)
            return {
              item_type: item.item_type,
              item_name: item.item_name,
              count: setting.count
            }
          })
          return row
        })
        this.total = data.count
      }).finally(() => {
        this.loading = false
      })
    },
    getItemsSetting (row) {
      const str = (row.items || []).map(item => {
        return item.count + item.item_name
      })
      return str.join(';')
    },
    /** 上架按钮操作 */
    handleSale (row) {
      this.$confirm('是否确认' + row.status === 'stop' ? '上架' : '下架' + '该加购包？加购包：' + row.name, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updatePackage({ id: row.id, status: row.status === 'stop' ? 'published' : 'stop' }).then(() => {
          this.getList()
          this.msgSuccess('操作成功')
        })
      })
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      this.$confirm(`是否确认删除该加购包？加购包：${row.name}`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updatePackage({ id: row.id, status: 'deleted' }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
      })
    },
    handleUpdate (row) {
      this.open = true
      this.$nextTick(() => {
        Object.keys(this.form).forEach(key => {
          this.form[key] = row[key]
        })
      })
    },
    onDeleteItems (index) {
      this.form.items.splice(index, 1)
    },
    onAddItems () {
      this.form.items.push(
        { key: Date.now(), item_type: null, count: undefined }
      )
    },
    submitForm (status) {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const params = Object.assign({ }, this.form)
          params.items = params.items.map(item => {
            const setting = JSON.stringify({ count: item.count })
            return {
              setting,
              item_type: item.item_type

            }
          })
          let fn = updatePackage
          if (!this.form.id) {
            params.status = status
            fn = addPackage
          }
          this.saveLoading = true
          fn(params).then(() => {
            this.getList()
            this.open = false
            this.msgSuccess(this.form.id ? '修改成功' : '创建成功')
          }).finally(() => {
            this.saveLoading = false
          })
        }
      })
    },
    onDialogClosed () {
      this.resetForm('form')
      this.form.id = null
      this.form.items = [
        { key: Date.now(), item_type: null, count: undefined }
      ]
    }
  }
}
</script>
